package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.BlocksDAO;
import com.hanoi.wiki.dao.CoordinatesDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.CoordinatesManager;
import com.hanoi.wiki.model.Blocks;
import com.hanoi.wiki.model.Coordinates;
import com.hanoi.wiki.model.json.CoordinatesJson;

@Component
@Transactional
public class CoordinatesManagerImpl extends BaseManagerImpl implements CoordinatesManager{
	
	@Autowired
	private CoordinatesDAO coordinatesDAO;
	
	@Autowired
	private BlocksDAO blocksDAO;
	
	public int save(CoordinatesJson json) {
		try {
			Coordinates coor = new Coordinates(json);
			
			List<Blocks> blocks = new ArrayList<Blocks>();
			Blocks block;
			for(Integer i : json.getBlocks()) {
				block = blocksDAO.get(i);
				if(block != null) {
					blocks.add(block);
				}
			}
			
			coor.setBlocks(blocks);
			
			return coordinatesDAO.saveCoordinates(coor);
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return 0;
	}

	
	public void update(CoordinatesJson json) {
		try {
			Coordinates coor = new Coordinates(json);
			
			List<Blocks> blocks = new ArrayList<Blocks>();
			Blocks block;
			for(Integer i : json.getBlocks()) {
				block = blocksDAO.get(i);
				if(block != null) {
					blocks.add(block);
				}
			}
			
			coor.setId(json.getId());
			coor.setBlocks(blocks);
			
			coordinatesDAO.update(coor);
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}

	
	public CoordinatesJson get(Integer id) {
		try {
			return new CoordinatesJson(coordinatesDAO.get(id));
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return null;
	}

	
	public List<CoordinatesJson> getList() {
		List<CoordinatesJson> coorJList = new ArrayList<CoordinatesJson>();
		List<Coordinates> coorList = coordinatesDAO.getList();
		try {
			for(Coordinates coordinates : coorList) {
				coorJList.add(new CoordinatesJson(coordinates));
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return coorJList;
	}

	public void remove(Integer id) {
		try {
			if(coordinatesDAO.get(id) != null) {
				coordinatesDAO.remove(id);
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}
}
